﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AudioCore.Entity;
using System.Data;
using System.Reflection;
using AudioCore.Common;
using System.Diagnostics;

namespace AudioCore.Biz
{
    public abstract class BaseBiz : IDisposable
    {
        protected static TraceLog _ts = new TraceLog(Common.Constant.TraceSourceName.General, SourceLevels.All);

        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }

        public static BaseEntity MapDataRowToObject(DataRow row, Type type)
        {
            BaseEntity obj = (BaseEntity)Activator.CreateInstance(type);
            foreach (PropertyInfo property in type.GetProperties())
            {
                try
                {
                    object[] arrMapping = property.GetCustomAttributes(typeof(PropertyEntity), true);
                    if (arrMapping != null && arrMapping.Length > 0)
                    {
                        PropertyEntity objMapping = (PropertyEntity)arrMapping[0];
                        if (objMapping != null && row.Table.Columns.Contains(objMapping.ColumnName)
                            && row[objMapping.ColumnName] != DBNull.Value)
                        {
                            property.SetValue(obj, row[objMapping.ColumnName], null);
                        }
                    }
                }
                catch (Exception e)
                {
                    //Do nothing
                }
            } 
            return obj;

        }

        public static List<BaseEntity> MapDataTableToList(DataTable table, Type type)
        {
            List<BaseEntity> entities = new List<BaseEntity>();
            foreach (DataRow row in table.Rows)
            {
                BaseEntity entity = MapDataRowToObject(row, type);
                if (entity != null)
                {
                    entities.Add(entity);
                }
            }
            return entities;
        }
    }
}
